package com.xiaoyao.myframeapp.utils.RichScan;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xiaoyao.myframeapp.R;
import com.xiaoyao.myframeapp.mvp.base.BaseActivityNo;
import com.xiaoyao.myframeapp.utils.SpUtils;
import com.xiaoyao.myframeapp.utils.ToastUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 定制化显示扫描界面
 */
public class SecondActivity extends BaseActivityNo {

    @BindView(R.id.fl_my_container)
    FrameLayout flMyContainer;
    @BindView(R.id.activity_second)
    RelativeLayout activitySecond;
    @BindView(R.id.capture_light_btn)
    Button captureLightBtn;
    @BindView(R.id.capture_picture_btn)
    Button capturePictureBtn;
    private CaptureFragment captureFragment;
    private String userId = SpUtils.get("id", 0).toString();//TODO ID
    /**
     * 选择系统图片Request Code
     */
    private static final int REQUEST_IMAGE = 112;

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_second);
//
//
//        captureFragment = new CaptureFragment();
//        // 为二维码扫描界面设置定制化界面
//        CodeUtils.setFragmentArgs(captureFragment, R.layout.a_my_camera);
//        captureFragment.setAnalyzeCallback(analyzeCallback);
//        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
//
//        initView();
//    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_second;
    }

    private boolean isOneinitView = true;

    @Override
    protected void initView() {
        if (isOneinitView) {
            isOneinitView = false;

            captureFragment = new CaptureFragment();
            // 为二维码扫描界面设置定制化界面
            CodeUtils.setFragmentArgs(captureFragment, R.layout.a_my_camera);
            captureFragment.setAnalyzeCallback(analyzeCallback);
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();

        }

        getPersimmions();
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void showLoading() {

    }

    @Override
    protected void hideLoading() {

    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
            bundle.putString(CodeUtils.RESULT_STRING, result);
            resultIntent.putExtras(bundle);
            SecondActivity.this.setResult(RESULT_OK, resultIntent);
            SecondActivity.this.finish();
        }

        @Override
        public void onAnalyzeFailed() {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "");
            resultIntent.putExtras(bundle);
            SecondActivity.this.setResult(RESULT_OK, resultIntent);
            SecondActivity.this.finish();
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //TODO 直接扫描在fm处理了
        /**
         * 选择系统图片并解析
         */
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                final Uri uri = data.getData();
                try {
                    CodeUtils.analyzeBitmap(ImageUtil.getImageAbsolutePath(this, uri), new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
//                            Toast.makeText(SecondActivity.this, "解析结果:" + result, Toast.LENGTH_LONG).show();

                            RichScanDisposeLogic.RichScan_Dispose(SecondActivity.this, result, userId);
//                            finish();
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            Toast.makeText(SecondActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == REQUEST_CAMERA_PERM) {
//            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
//                    .show();
        }
    }

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;

    public static boolean isOpen = false;

    @OnClick({R.id.capture_light_btn, R.id.capture_picture_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.capture_light_btn:
                //TODO 手电筒
                if (!isOpen) {
                    CodeUtils.isLightEnable(true);
                    captureLightBtn.setSelected(true);
                    isOpen = true;
                } else {
                    CodeUtils.isLightEnable(false);
                    captureLightBtn.setSelected(false);
                    isOpen = false;
                }
                break;
            case R.id.capture_picture_btn:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    final private static int REQUEST_CODE_CAMERA = 123;

    public void getPersimmions() {
        ////判断当前是否是6.0版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 拍照权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // SD卡  android.permission-group.STORAGE
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);

            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), REQUEST_CODE_CAMERA);
            } else {
                //当拍照 权限都有时，开始
                getPatIamge();
            }
        } else {
            ///低于6.0以下，开始
            getPatIamge();
        }
    }

    public void getPatIamge() {
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    getPatIamge();
//                    ToastUtil.setToast("拍照权限获取成功");

                } else {
                    // Permission Denied
                    ToastUtil.setToast("照相机权限获取失败！");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
